package org.zjvis.datascience.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.commons.lang3.StringUtils;

/**
 * @description 网络地址诊断工具类
 * @date 2021-11-09
 */
public class NetworkUtil {

    public static String determineIpAddress() throws SocketException {
        SocketException caughtException = null;
        for (final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
            try {
                final NetworkInterface nextInterface = networkInterfaces.nextElement();
                if (!nextInterface.isLoopback() && !nextInterface.isVirtual() && !nextInterface.isPointToPoint()) {
                    for (final Enumeration<InetAddress> addresses = nextInterface.getInetAddresses(); addresses.hasMoreElements(); ) {
                        final InetAddress inetAddress = addresses.nextElement();
                        final byte[] address = inetAddress.getAddress();
                        if ((address.length == 4) && ((address[0] != 127) || (address[1] != 0))) {

                            String hostname = inetAddress.getCanonicalHostName();
                            if (StringUtils.isEmpty(hostname)) {

                            }
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            } catch (SocketException ex) {
                caughtException = ex;
            }
        }

        if (caughtException != null) {
            throw caughtException;
        }
        return null;
    }

}
